﻿#include "viewer.h"
#include "ui_viewer.h"

Viewer::Viewer(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Viewer)
{
    ui->setupUi(this);

    table=G_LOCATION;
    tagTable=G_TAG;
    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);
    ui->tableView->verticalHeader()->hide();
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateFolderView();
    createMenu();
    loadResLocation();
}

Viewer::~Viewer()
{
    delete ui;
}

void Viewer::generateMenu()
{
    menu->addAction(QStringLiteral("更新列表 (F4)"),this,&Viewer::updateFolderView);
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&Viewer::updateView);
    menu->addSeparator();
    QMenu *optMenu=menu->addMenu(QStringLiteral("选项"));
    optMenu->addAction(QStringLiteral("打开所在目录 (F9)"),this,&Viewer::setResLocation);
    optMenu->addAction(QStringLiteral("打开资源目录 (F10)"),this,&Viewer::openResLocation);
    optMenu->addAction(QStringLiteral("设置资源目录"),this,&Viewer::setResLocation);
    optMenu->addSeparator();
    optMenu->addAction(QStringLiteral("保存标签 (Ctrl+S)"),this,&Viewer::updateTag);
    optMenu->addSeparator();
    optMenu->addAction(QStringLiteral("更新资源"),this,&Viewer::updateResource);
}

void Viewer::updateFolderView()
{
    if(listModel->rowCount() != 0)
        listModel->setStringList(QStringList());

    QStringList items=sp_getCategory(table);
    if(!items.isEmpty())
        listModel->setStringList(items);
}

void Viewer::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
        updateTag();
    else
    {
        switch (event->key()) {
        case Qt::Key_F4:
            updateFolderView();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        case Qt::Key_F9:
            openItemLocation();
            break;
        case Qt::Key_F10:
            openResLocation();
            break;
        }
    }
}

void Viewer::setResLocation()
{
    QString path=QFileDialog::getExistingDirectory(this,QStringLiteral("选择资源目录"));
    if(!path.isEmpty())
    {
        resLocation=path;
        saveResLocation();
    }
}

void Viewer::saveResLocation()
{
    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    cfg.setValue("Location/resLocation",resLocation);
}

void Viewer::loadResLocation()
{
    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    if(cfg.contains("Location/resLocation"))
        resLocation=cfg.value("Location/resLocation").toString();
}

void Viewer::openResLocation()
{
    if(resLocation.isEmpty())
        return;

    if(QFileInfo::exists(resLocation))
        QDesktopServices::openUrl(QUrl::fromLocalFile(resLocation));
}

void Viewer::openItemLocation()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
    {
        QString detail=sp_fetchString(index,DET_COL);
        QString dir=QFileInfo(detail).dir().path();
        if(QFileInfo::exists(dir))
            QDesktopServices::openUrl(QUrl::fromLocalFile(dir));
    }
}

void Viewer::updateView()
{
    if(selectFolder.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("category='%1'").arg(selectFolder));
    model->select();

    ui->tableView->hideColumn(ID_COL);
    ui->tableView->hideColumn(CAT_COL);
    model->setHeaderData(LAB_COL,Qt::Horizontal,QStringLiteral("名称"));    //label
    ui->tableView->hideColumn(DET_COL);
    ui->tableView->hideColumn(ADD_COL);
}

void Viewer::on_tableView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectLabel=sp_fetchString(index,LAB_COL);
        selectDetail=sp_fetchString(index,DET_COL);
        selectAddition=sp_fetchString(index,ADD_COL);   //size_

        QString tag=sp_getItem("detail",tagTable,"addition",selectAddition).toString();
        if(!tag.isEmpty())
        {
            isNewTag=false;
            ui->tag->setPlainText(tag);
        }
        else
        {
            isNewTag=true;
            ui->tag->clear();
        }
    }
}

void Viewer::on_tableView_doubleClicked(const QModelIndex &)
{
    if(selectDetail.isEmpty())
        return;

    if(QFileInfo::exists(selectDetail))
        QDesktopServices::openUrl(QUrl::fromLocalFile(selectDetail));
}

void Viewer::on_kw_returnPressed()
{
    QString kw=ui->kw->text().trimmed();
    if(kw.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("label like '%%1%'").arg(kw));
    model->select();

    ui->tableView->hideColumn(ID_COL);
    ui->tableView->hideColumn(CAT_COL);
    model->setHeaderData(LAB_COL,Qt::Horizontal,QStringLiteral("名称"));    //label
    ui->tableView->hideColumn(DET_COL);
    ui->tableView->hideColumn(ADD_COL);
}

void Viewer::on_listView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectFolder=index.data().toString();
        updateView();
    }
}

void Viewer::updateResource()
{
    if(resLocation.isEmpty()){
        QMessageBox::warning(this,QStringLiteral("无效操作"),QStringLiteral("未设置资源目录，无法操作！"));
        return;
    }

    if(!QFileInfo::exists(resLocation))
    {
        QMessageBox::warning(this,QStringLiteral("无效操作"),QStringLiteral("资源目录不存在，无法操作！"));
        return;
    }

    if(sp_truncateTable(table))
        scanRescource();
    else
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("异常情况，无法操作数据库！"));
}

void Viewer::scanRescource()
{
    QDirIterator dirIter(resLocation,QDir::Files,
                         QDirIterator::Subdirectories);

    QSqlQuery query;
    QSqlDatabase::database().transaction();
    while (dirIter.hasNext()) {
        dirIter.next();

        QFileInfo fileInfo=dirIter.fileInfo();
        query.prepare(QString("insert into %1 (category,label,detail,addition) values (?,?,?,?)")
                      .arg(table));
        query.addBindValue(fileInfo.dir().dirName());
        query.addBindValue(fileInfo.fileName());
        query.addBindValue(fileInfo.filePath());
        query.addBindValue(fileInfo.size());
        query.exec();
    }
    QSqlDatabase::database().commit();
    updateFolderView();
}

void Viewer::updateTag()
{
    if(selectLabel.isEmpty())
        return;

    QString tag=ui->tag->toPlainText();
    QSqlQuery query;
    bool result=false;

    if(isNewTag)
    {
        if(tag.isEmpty())
            return;

        isNewTag=false;
        query.prepare(QString("insert into %1 (label,detail,addition) values (?,?,?)")
                      .arg(tagTable));
        query.addBindValue(selectLabel);
        query.addBindValue(tag);
        query.addBindValue(selectAddition);
        result=query.exec();
    }
    else
    {
        QString sql=QString("update %1 set label='%2',detail='%3' where addition='%4'")
                .arg(tagTable)
                .arg(selectLabel)
                .arg(tag)
                .arg(selectAddition);
        result=query.exec(sql);
    }

    if(!result)
        MESSAGE_CANNOT_UPDATE
}
